package com.amos.generate.util;

import com.amos.generate.bean.BaseField;
import com.amos.util.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Copyright © 2018 嘉源锐信. All rights reserved.
 *
 * @Project: mu-exam
 * @ClassName: VelocityUtils
 * @Package: com.amos.generate.util
 * @author: zhuqb
 * @Description:
 * @date: 2020/3/10 0010 上午 11:54
 * @Version: V1.0
 */
public class VelocityUtils {
    private static final Logger logger = LoggerFactory.getLogger(VelocityUtils.class);
    private static final String POINT = ".";

    private static final Pattern LINEP_ATTERN = Pattern.compile("_(\\w)");
    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    public static final Map<String, String> COLUMN_TYPE_REFLECT_DATA_TYPE = new HashMap<>();
    public static final Map<String, String> JAVA_TYPE_IMPORT = new HashMap<>();

    static {
        COLUMN_TYPE_REFLECT_DATA_TYPE.put("tinyint", "Integer");
        COLUMN_TYPE_REFLECT_DATA_TYPE.put("datetime", "Date");
        COLUMN_TYPE_REFLECT_DATA_TYPE.put("date", "Date");
        COLUMN_TYPE_REFLECT_DATA_TYPE.put("decimal", "BigDecimal");
        COLUMN_TYPE_REFLECT_DATA_TYPE.put("double", "Double");
        COLUMN_TYPE_REFLECT_DATA_TYPE.put("float", "Long");
        JAVA_TYPE_IMPORT.put("date", "java.util.Date;");
        JAVA_TYPE_IMPORT.put("datetime", "java.util.Date;");
        JAVA_TYPE_IMPORT.put("decimal", "java.math.BigDecimal;");
    }

    /**
     * 获取VelocityEngine
     *
     * @return
     */
    public static VelocityEngine getVelocityEngine() {
        // 初始化参数
        Properties properties = new Properties();
        properties.setProperty("resource.loader", "class");
        properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        VelocityEngine velocityEngine = new VelocityEngine(properties);
        return velocityEngine;
    }

    /**
     * 将BaseField中的字段转化成VelocityContext对象
     *
     * @param baseField
     * @return
     */
    public static VelocityContext parseFieldToVelocityContext(BaseField baseField) {
        VelocityContext context = new VelocityContext();
        Field[] fields = FieldUtils.getAllFields(baseField.getClass());
        for (Field field : fields) {
            field.setAccessible(Boolean.TRUE);
            try {
                context.put(field.getName(), field.get(baseField));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return context;

    }

    /**
     * 下划线转驼峰
     *
     * @param str
     * @return
     */
    public static String underline2Camel(String str) {
        str = str.toLowerCase();
        Matcher matcher = LINEP_ATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线
     *
     * @param str
     * @return
     */
    public static String camel2Underline(String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 包路径名 转化为 文件夹名
     *
     * @param packageName
     * @return
     */
    public static String packageName2Dir(String packageName) {
        if (StringUtils.isNullOrEmpty(packageName)) {
            return "";
        }
        packageName = packageName.replaceAll("\\" + POINT, Matcher.quoteReplacement(File.separator));

        return packageName;
    }

    /**
     * 创建文件夹
     *
     * @param filePath
     * @return
     */
    public static boolean createDir(String filePath) {
        if (StringUtils.isNullOrEmpty(filePath)) {
            return false;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return true;
    }

    public static boolean createFile(File file) {
        if (StringUtils.isNullOrEmpty(file)) {
            return false;
        }

        logger.info("createFile:{}", file.getAbsolutePath());

        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 根据表明获取访问的路径
     * 表名  分为两部分，模块_业务表名
     * <p>
     * 如果业务表名也存在_ 则 业务表名以 - 连接
     *
     * @param tableName
     * @return
     */
    public static String getRequestPath(String tableName) {
        if (StringUtils.isNullOrEmpty(tableName)) {
            return null;
        }

        String[] tableNameArr = tableName.split("_");

        List<String> list = Arrays.asList(tableNameArr);
        if (list.size() < 2) {
            return null;
        }
        return list.stream().filter(item -> !item.equals(list.get(0))).collect(Collectors.joining("-"));
    }
}
